const { ethers } = require("hardhat");
const fs = require("fs");
const path = require("path");

async function main() {
    console.log("🔄 在 Ganache 上升级代理合约...\n");

    const [deployer] = await ethers.getSigners();
    console.log(`📝 操作者地址: ${deployer.address}`);

    // 从部署记录文件读取代理合约地址
    const deploymentFile = path.join(__dirname, 'deployment-ganache.json');
    let PROXY_ADDRESS;

    try {
        if (fs.existsSync(deploymentFile)) {
            const deployment = JSON.parse(fs.readFileSync(deploymentFile, 'utf8'));
            PROXY_ADDRESS = deployment.proxy;
            console.log(`📋 代理合约地址: ${PROXY_ADDRESS}`);
        } else {
            console.log("❌ 未找到部署记录，请先运行部署脚本");
            return;
        }
    } catch (error) {
        console.log("❌ 读取部署记录失败:", error.message);
        return;
    }

    // 部署逻辑合约 V2
    console.log("\n📦 部署 LogicContractV2...");
    const LogicContractV2 = await ethers.getContractFactory("LogicContractV2");
    const logicV2 = await LogicContractV2.deploy();
    await logicV2.waitForDeployment();
    const logicV2Address = await logicV2.getAddress();
    console.log(`✅ LogicContractV2 部署成功: ${logicV2Address}`);

    // 获取代理合约实例
    const proxy = await ethers.getContractAt("ProxyContract", PROXY_ADDRESS);

    // 升级到 V2
    console.log("\n⬆️  升级到 V2...");
    const upgradeTx = await proxy.upgrade(logicV2Address);
    await upgradeTx.wait();
    console.log("✅ 升级成功");

    // 将代理合约附加 LogicContractV2 的 ABI
    const proxyAsV2 = await ethers.getContractAt("LogicContractV2", PROXY_ADDRESS);

    // 初始化 V2 合约
    console.log("\n🔧 初始化 V2 合约...");
    const initTx = await proxyAsV2.initialize();
    await initTx.wait();
    console.log("✅ V2 合约初始化成功");

    // 测试 V2 新功能
    console.log("\n🧪 测试 V2 新功能...");

    // 验证数据持久性
    const number = await proxyAsV2.getNumber();
    console.log(`✅ 升级后 number 保持不变: ${number}`);

    // 测试新功能
    await proxyAsV2.setMessage("Hello from Ganache V2!");
    const message = await proxyAsV2.message();
    console.log(`✅ 消息内容: ${message}`);

    await proxyAsV2.setNumber(10);
    await proxyAsV2.multiplyNumber(3);
    const multipliedNumber = await proxyAsV2.getNumber();
    console.log(`✅ 乘法运算后 number = ${multipliedNumber}`);

    const version = await proxyAsV2.version();
    console.log(`✅ 新版本: ${version}`);

    // 保存升级信息
    const upgradeInfo = {
        logicV2: logicV2Address,
        proxy: PROXY_ADDRESS,
        upgradedAt: new Date().toISOString(),
        deployer: deployer.address
    };

    const upgradeFile = path.join(__dirname, 'upgrade-ganache.json');
    fs.writeFileSync(upgradeFile, JSON.stringify(upgradeInfo, null, 2));
    console.log("\n📋 升级信息已保存");

    console.log("\n🎉 Ganache 升级完成！");
}

main()
    .then(() => process.exit(0))
    .catch((error) => {
        console.error("❌ 升级失败:", error);
        process.exit(1);
    });